package com.study.interceptor;

import com.study.annotations.LoginRequired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 拦截器
 *
 * @创建时间 2020/4/21 14:34
 */
@Slf4j
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    /**
     * 问题 访问静态文件提示|ResourceHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
     * 拦截器拦截的内容
     * 1.拦截器com.study.web.HelloController#hello(ModelMap, RedirectAttributes)
     * 2.拦截器org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
     * 3.拦截器com.study.web.InteLoginController#isNeedLogin()
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //URL=http://127.0.0.1:9590/error|/error
        log.info("|拦截器|URL={}|{}", request.getRequestURL(), request.getRequestURI());
        //System.out.println("拦截器"+handler);
        //TODO 判断拦截的请求的访问的注解|但是访问静态资源时提示|ResourceHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
        if (handler instanceof HandlerMethod) {
            HandlerMethod mh = (HandlerMethod) handler;
            LoginRequired loginRequired = mh.getMethodAnnotation(LoginRequired.class);
            if (loginRequired != null) {
                //TODO 需要登录
                boolean b = loginRequired.loginSuccess();
                System.out.println(b);
            }
        }


        return true;
    }

    private Method getCurrentMethod(Object invocation) throws Exception {
        HandlerMethod method = (HandlerMethod) invocation;
        //TODO 此处获取的是 controlller 类
        Class<?> beanType = method.getBeanType();
        System.out.println(beanType.getAnnotation(RequestMapping.class));
        //TODO 此处获取的执行的方法
        return method.getMethod();
    }

    public boolean preHandleDeom01(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.getRequestURI();
        //URL=http://127.0.0.1:9590/error|/error
        log.info("|拦截器|URL={}|{}", request.getRequestURL(), request.getRequestURI());

        //TODO 判断拦截的请求的访问的注解
        HandlerMethod mh = (HandlerMethod) handler;
        LoginRequired loginRequired = mh.getMethodAnnotation(LoginRequired.class);
        if (loginRequired == null) {
            //TODO 需要登录
            if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {// 是ajax请求
                //response.setCharacterEncoding("text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                StringBuffer jsonTip = new StringBuffer("{\"result\":");
                jsonTip.append(false).append(",\"tip\":\"您无权操作\"}");
                writer.print(jsonTip.toString());
                return false;
            } else {// 非ajax请求
                String content = request.getSession().getServletContext().getContextPath();
                // response.sendRedirect(content + "/refuse.html");//转发到页面
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("您无权操作呀！");
                return false;
            }
        }


        return true;
    }
}
